package com.lyp.yangxixi.missionfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ajguan.library.EasyRefreshLayout;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.activitys.CarMyYiyuyueActivity;
import com.lyp.activitys.DectionMyYiyuyueActivity;
import com.lyp.activitys.IndoorMyYiyuyueActivity;
import com.lyp.adapters.MYesyuyueAdapter;
import com.lyp.jsonbean.LoginBean;
import com.lyp.jsonbean.MYesyuyueBean;
import com.tjl.yangxixis.OriginalFragment;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.activity.MainActivity;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 
 * @author Administrator
 */
//已预约
public class YesYuYueFragment extends OriginalFragment{
	
	
	View v;

	private RecyclerView mRecyclerView;
	private MYesyuyueAdapter mAdapter;
	private LinearLayoutManager mLinearLayoutManager;
	private List<MYesyuyueBean.DataBean> mList = new ArrayList<>();
	private LoginBean.DataBean bean;
	private TextView mCounts;
	//定义一个页码为1
	int pages=1;
	private EasyRefreshLayout mEasyRefreshLayout;
    private int mPosition;

	public View createView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 v= inflater.inflate(R.layout.fragment_allmission, null,true);
		init();
		LogUtils.i("tag","33333333");
		return v;
	}

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
		
	}

	public void init(){
		bean = ((MainActivity)getActivity()).dataBean;
		mCounts = (TextView) v.findViewById(R.id.tv_counts);
		mRecyclerView = (RecyclerView) v.findViewById(R.id.grid_recycler);
		mLinearLayoutManager = new LinearLayoutManager(getActivity());
		mRecyclerView.setLayoutManager(mLinearLayoutManager);
		mAdapter = new MYesyuyueAdapter(mList);
		// 实例化 RecyclerView Adapter
		mRecyclerView.setAdapter(mAdapter);
		mAdapter.setOnItemClickListener(new MYesyuyueAdapter.MyItemClickListener() {
			@Override
			public void onItemClick(View v, int position) {
				if (bean.getServer_select().equals("车内空气净化服务")) {
					Intent intentcar = new Intent(getActivity(), CarMyYiyuyueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
                    mPosition = position;
					intentcar.putExtras(bundle);
                    startActivityForResult(intentcar, 0x301);
				}
				else if (bean.getServer_select().equals("第三方检测服务")){
					Intent intentdection = new Intent(getActivity(), DectionMyYiyuyueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
                    mPosition = position;
					intentdection.putExtras(bundle);
                    startActivityForResult(intentdection, 0x301);
				}
				else if (bean.getServer_select().equals("室内空气净化服务")){
					Intent intentindoor = new Intent(getActivity(), IndoorMyYiyuyueActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("databean",mList.get(position));
                    mPosition = position;
					intentindoor.putExtras(bundle);
                    startActivityForResult(intentindoor, 0x301);
				}
			}
		});

		try {
			MYesTaskRefresh(bean.getId(),pages);
		} catch (IOException e) {
			e.printStackTrace();
		}

		mEasyRefreshLayout = (EasyRefreshLayout) v.findViewById(R.id.easylayout);
		mEasyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
			@Override
			public void onLoadMore() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							MYesTaskLoadMore(bean.getId(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.loadMoreComplete();
							}
						});
					}
				}).start();
			}

			@Override
			public void onRefreshing() {
				new Thread(new Runnable() {
					@Override
					public void run() {
						SystemClock.sleep(1000);
						try {
							MYesTaskRefresh(bean.getId(),pages);
						} catch (IOException e) {
							e.printStackTrace();
						}
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mEasyRefreshLayout.refreshComplete();
							}
						});
					}
				}).start();
			}
		});
	}

	//刷新
	public void MYesTaskRefresh(String a_id,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<MYesyuyueBean> call = github.getMYestask(a_id,page);
		call.enqueue(new Callback<MYesyuyueBean>() {
			@Override
			public void onResponse(Call<MYesyuyueBean> call, final Response<MYesyuyueBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mList.clear();
							mList.addAll(response.body().getData());
							mAdapter.notifyDataSetChanged();
							if (response.body().getNext_page() > 0) {
								pages++;
							} else {
								Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
							}
						}
					});
				}else {
					Toast.makeText(getActivity(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
				}
			}
			@Override
			public void onFailure(Call<MYesyuyueBean> call, Throwable t) {
				ToastUtils.showShort(t.getMessage());
			}
		});
	}

	//加载
	public void MYesTaskLoadMore(String a_id,int page) throws IOException {
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(YangxixiApi.APP_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.build();
		YangxixiApi github = retrofit.create(YangxixiApi.class);
		Call<MYesyuyueBean> call = github.getMYestask(a_id,page);
		call.enqueue(new Callback<MYesyuyueBean>() {
			@Override
			public void onResponse(Call<MYesyuyueBean> call, final Response<MYesyuyueBean> response) {
				if (response.body().getResult()== 1 ) {
					mCounts.setText(response.body().getCounts());
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mList.clear();
							mList.addAll(response.body().getData());
							mAdapter.notifyDataSetChanged();
							if (pages >= 1) {
								pages--;
							} else {
								Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
							}
						}
					});
				}else {
					Toast.makeText(getActivity(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
				}
			}
			@Override
			public void onFailure(Call<MYesyuyueBean> call, Throwable t) {
				ToastUtils.showShort(t.getMessage());
			}
		});
	}


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            try {
                MYesTaskRefresh(bean.getId(),pages);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if (resultCode == 3001){
            switch (requestCode) {
                case 0x301:
                    mList.remove(mPosition);
                    mCounts.setText(mList.size()+"");
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

}
